package com.fiberhome.opticalbox.ui.fragment.frame;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.Button;

import com.fiberhome.opticalbox.R;
import com.fiberhome.opticalbox.App;
import com.fiberhome.opticalbox.BaseFragment;
import com.fiberhome.opticalbox.C;
import com.fiberhome.opticalbox.net.NetConstant;
import com.fiberhome.opticalbox.net.NetManager.TcpErrorListener;
import com.fiberhome.opticalbox.net.NetManager.TcpListener;
import com.fiberhome.opticalbox.net.bean.Parameter;
import com.fiberhome.opticalbox.net.utils.JsonUtil;
import com.fiberhome.opticalbox.ui.MainActivity;
import com.fiberhome.opticalbox.ui.RemoteCtrlActivity;
import com.fiberhome.opticalbox.ui.SurfCheckActivity;
import com.fiberhome.opticalbox.ui.SurfCtrlActivity;
import com.fiberhome.opticalbox.ui.SurfManageActivity;
import com.fiberhome.opticalbox.ui.SurfModeActivity;
import com.fiberhome.opticalbox.ui.WifiModeActivity;
import com.fiberhome.opticalbox.utils.AnimUtil;
import com.fiberhome.opticalbox.utils.NetworkUtil;
import com.fiberhome.opticalbox.view.SpeedCheckingView;
import com.fiberhome.remoteime.hisilicon.multiscreen.mybox.DeviceDiscoveryActivity;

/**
 * @description 主页碎片
 * @author wangpeng
 * @date 2014-12-22
 */
public class MainFragment extends BaseFragment {

	private MainActivity holder;

	private Button btnSpeedChecking;
	private SpeedCheckingView speedCheckingView;
	private View layLeftMenu;

	@Override public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof MainActivity) {
			holder = (MainActivity) activity;
		}
		registerChildTcpListener(tcpListener);
		registerChildTcpErrorListener(tcpErrorListener);
	}

	@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.ob_fragment_main, null);

		view.findViewById(R.id.lay_surf_check).setOnClickListener(onClickListener);
		view.findViewById(R.id.lay_surf_master_ctrl).setOnClickListener(onClickListener);
		view.findViewById(R.id.lay_surf_private).setOnClickListener(onClickListener);
		view.findViewById(R.id.lay_surf_mode).setOnClickListener(onClickListener);
		view.findViewById(R.id.lay_wifi_mode).setOnClickListener(onClickListener);
		view.findViewById(R.id.lay_remote_ctrl).setOnClickListener(onClickListener);

		layLeftMenu = view.findViewById(R.id.lay_left_menu);
		layLeftMenu.setOnClickListener(toggleLeftMenuListener);

		speedCheckingView = (SpeedCheckingView) view.findViewById(R.id.view_speed_checking);
		btnSpeedChecking = (Button) view.findViewById(R.id.btn_speed_checking);
		btnSpeedChecking.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				btnSpeedChecking.setEnabled(false);
				speedCheckingView.reset();
				clearSpeedRateData();
				requestSetHttpCFG();
			}
		});

		return view;
	}

	private OnClickListener toggleLeftMenuListener = new OnClickListener() {
		@Override public void onClick(View view) {
			if (holder != null) {
				startAnimation(view, AnimUtil.init().addAlpha(1f, 0f, 0, 200, new LinearInterpolator(), Animation.REVERSE).create());
				holder.slidingMenuToggle();
			}
		}
	};

	private OnClickListener onClickListener = new OnClickListener() {
		@Override public void onClick(View view) {
			if (holder != null) {
				switch (view.getId()) {
				case R.id.lay_surf_master_ctrl:
					holder.actionStart(SurfCtrlActivity.class);
					break;
				case R.id.lay_surf_check:
					holder.actionStart(SurfCheckActivity.class);
					break;
				case R.id.lay_wifi_mode:
					holder.actionStart(WifiModeActivity.class);
					break;
				case R.id.lay_surf_mode:
					holder.actionStart(SurfModeActivity.class);
					break;
				case R.id.lay_remote_ctrl:
					toRemoteCtrl();
					break;
				case R.id.lay_surf_private:
					holder.actionStart(SurfManageActivity.class);
					break;
				}
			}
		}

		private void toRemoteCtrl() {
			if (C.app.productType_MR828.equals(App.i().productType)) {
				holder.actionStart(DeviceDiscoveryActivity.class);
			} else {
				holder.actionStart(RemoteCtrlActivity.class);
			}
		}
	};

	private void requestSetHttpCFG() {
		if (netManager != null) {
			netManager.sendTcp(JsonUtil.get_SET_HTTP_CFG(App.i().username, App.i().password, C.app.speedTestAddress));
		}
	}

	private void requestStartHttpDownload() {
		if (netManager != null) {
			netManager.sendTcp(JsonUtil.startHttpDownloaRequest(App.i().username, App.i().password, "Start",
					String.valueOf(C.app.speedTestTime)));
		}
	}

	private void requestRealtimeRate() {
		if (netManager != null) {
			netManager.sendTcp(JsonUtil.get_GET_REALTIME_RATE(App.i().username, App.i().password));
		}
	}

	private int currTestTime = 0;
	private final float[] speedRate = new float[C.app.speedTestTime];

	private TcpListener tcpListener = new TcpListener() {

		@Override public void onReceive(String cmdType, Parameter param) {
			if (NetConstant.SET_HTTP_CFG.equals(cmdType)) {
				requestStartHttpDownload();
			} else if (NetConstant.HTTP_DOWNLOAD_REQUEST.equals(cmdType)) {
				requestRealtimeRate();
			} else if (NetConstant.GET_REALTIME_RATE.equals(cmdType)) {
				String result = param.RealTimeRate;
				if (TextUtils.isEmpty(result)) {
					speedRate[currTestTime] = 0f;
				} else {
					speedRate[currTestTime] = Float.parseFloat(param.RealTimeRate);
				}

				currTestTime++;
				speedCheckingView.progress(getMaxValueInArray(speedRate));
				if (currTestTime < C.app.speedTestTime) {
					handler.postDelayed(new Runnable() {
						@Override public void run() {
							requestRealtimeRate();
						}
					}, 1000);
				} else {
					currTestTime = 0;
					btnSpeedChecking.setEnabled(true);
					speedCheckingView.setSpeedInfoTextColor(0xfffff7b2);
				}
			}
		}
	};

	private float getMaxValueInArray(float[] speedRate) {
		float max = 0;
		for (int i = 0; i < speedRate.length; i++) {
			if (speedRate[i] > max) {
				max = speedRate[i];
			}
		}
		float tmpRatio = (100 - (C.app.speedTestTime - currTestTime) * 2) / 100f;
		return max * tmpRatio;
	}

	private void clearSpeedRateData() {
		for (int i = 0; i < speedRate.length; i++) {
			speedRate[i] = 0;
		}
	}

	private TcpErrorListener tcpErrorListener = new TcpErrorListener() {
		@Override public void onError(String cmdType) {
			if (NetConstant.SET_HTTP_CFG.equals(cmdType)) {
				if (holder != null) {
					showToast(NetworkUtil.isDisconnected(holder) ? R.string.ob_error_net : R.string.ob_error_request);
				}
			} else if (NetConstant.HTTP_DOWNLOAD_REQUEST.equals(cmdType)) {
				showToast(R.string.ob_fail_http_download);
			} else if (NetConstant.GET_REALTIME_RATE.equals(cmdType)) {
				showToast(R.string.ob_fail_speed_test);
			}

			btnSpeedChecking.setEnabled(true);
			speedCheckingView.reset();
		}
	};

}
